package com.dwsoft.xml;

import com.thoughtworks.xstream.converters.reflection.ObjectAccessException;
import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;

import java.lang.reflect.Field;

/**
 * @author sqw
 * @version 1.0
 * @description 解决在XML中不指定其属性要保留javaBean中属性的默认值
 * @ClassName FieldDefaultValueProvider
 * @Date 2020/8/10
 * @since jdk1.8
 */
public class FieldDefaultValueProvider extends PureJavaReflectionProvider {

    /**
     * @param object 目标类的实例
     * @param fieldName XML中显示指明的字段
     * @param definedIn 父类或者类本身
     */
    @Override
    public void writeField(Object object, String fieldName, Object value, Class definedIn) {
        Field field = fieldDictionary.field(object.getClass(), fieldName, definedIn);//返回存在于xml中的字段
        validateFieldAccess(field);//验证字段可以被访问
        try {
            if (value instanceof String) {
                String trim = ((String)value).trim();//字符串首尾去空
                if(trim.length()==0)//如果是空字符串，则不做赋值，使用默认初始值
                    return;
                field.set(object,trim);
            }else{
                field.set(object, value);
            }
        } catch (IllegalArgumentException e) {
            throw new ObjectAccessException("Could not set field " + object.getClass() + "." + field.getName(), e);
        } catch (IllegalAccessException e) {
            throw new ObjectAccessException("Could not set field " + object.getClass() + "." + field.getName(), e);
        }
    }
}
